package org.example.runningforum.server;

import org.example.runningforum.mapper.IArticleMapper;
import org.example.runningforum.modle.Article;
import org.example.runningforum.modle.ArticleDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {
    @Autowired
    private IArticleMapper iArticleMapper;

    /**
     * 获取按创建时间排序的文章列表（内容截取前50个字符）
     */
    public List<ArticleDetail> selectArticlesByCreateTimeWithSummary() {
        // 1. 从数据库获取完整文章列表
        List<ArticleDetail> articles = iArticleMapper.selectArticlesByCreateTime();

        // 2. 处理每篇文章的内容
        for (ArticleDetail article : articles) {
            // 获取完整内容
            String content = article.getContent();

            // 截取前50个字符
            if (content != null && content.length() > 50) {
                // 截取前50个字符，并添加省略号
                article.setContent(content.substring(0, 50) + "...");
            }
            // 如果内容少于50个字符，保留原内容
        }

        return articles;
    }

    /**
     * 获取按浏览量排序的文章列表（内容截取前50个字符）
     */
    public List<ArticleDetail> selectArticlesByViewsWithSummary() {
        List<ArticleDetail> articles = iArticleMapper.selectArticlesByViews();

        for (ArticleDetail article : articles) {
            String content = article.getContent();
            if (content != null && content.length() > 50) {
                article.setContent(content.substring(0, 50) + "...");
            }
        }

        return articles;
    }


    public ArticleDetail selectArticleByArticleId(Long articleId){
        ArticleDetail articleDetail = iArticleMapper.selectArticleByArticleId(articleId);
        Integer n = articleDetail.getLevel();
        if(n==1){
            articleDetail.setLevelZT("见习");
        }else if(n==2){
            articleDetail.setLevelZT("精锐");
        }else {
            articleDetail.setLevelZT("资深");
        }
        return articleDetail;
    }


    public Integer selectArticleCount(){
        return iArticleMapper.selectArticleCount();
    }

    //插入文章
    public Integer insertArticle(Article article){
        Integer n = iArticleMapper.insertArticle(article);

        Integer id = Math.toIntExact(article.getArticleId());
        if(n==1){
            return id;
        }else {
            return 0;
        }
    }
}
